package com.lhd_gm.scheduledtasksystem.utils;
import com.lhd_gm.scheduledtasksystem.pojo.ShellTask;
import com.lhd_gm.scheduledtasksystem.pojo.UniversalEntity;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ShellExecutor {

    public static int executeScript(ShellTask shellTask,String shellPath) throws IOException, InterruptedException, TimeoutException {
        // 1. 构建命令
        List<String> command = new ArrayList<>();
        command.add("D:\\develop\\Git\\bin\\bash.exe");
        command.add(shellPath);
        List<String> scriptArgs = shellTask.getScriptArgs();
        if (scriptArgs != null) {
            command.addAll(shellTask.getScriptArgs());
        }

        // 2. 配置进程环境
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        String workDir = shellTask.getWorkDir();
        if (workDir != null) {
            processBuilder.directory(new File(workDir));
        }
        List<UniversalEntity> envVars = shellTask.getEnvVars();
        if (envVars != null) {
            for (UniversalEntity envVar : envVars) {
                processBuilder.environment().put(envVar.getKey(),envVar.getValue());
            }
        }
        // 合并错误流到标准输出
        processBuilder.redirectErrorStream(true);

        // 3. 启动进程
        Process process = processBuilder.start();

        // 4. 读取输出流（防止阻塞）
        StringBuilder output = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }
        }

        // 5. 等待执行完成或超时
        if (!process.waitFor(shellTask.getTimeout(), TimeUnit.SECONDS)) {
            process.destroyForcibly();
            throw new TimeoutException("脚本执行超时");
        }

        // 6. 返回退出码和输出
        int exitCode = process.exitValue();
        System.out.println("脚本执行结果 - Exit Code: " + exitCode + ", Output: "+output);
        return exitCode;
    }
}
